package com.smartfactory.sail.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.smartfactory.sail.entity.ItemWorkingprocedureDevice;
import com.smartfactory.sail.entity.OrderItem;
import com.smartfactory.sail.entity.enums.DeviceStatusEnum;
import com.smartfactory.sail.entity.enums.OrderItemStatusEnum;
import com.smartfactory.sail.mapper.ItemWorkingprocedureDeviceMapper;
import com.smartfactory.sail.service.IDeviceService;
import com.smartfactory.sail.service.IItemWorkingprocedureDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartfactory.sail.service.IOrderItemService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 产品工序设备 服务实现类
 * </p>
 *
 * @author 王巨壁
 * @since 2019-08-13
 */
@Service
@Transactional
public class ItemWorkingprocedureDeviceServiceImpl extends ServiceImpl<ItemWorkingprocedureDeviceMapper, ItemWorkingprocedureDevice> implements IItemWorkingprocedureDeviceService {
    private ItemWorkingprocedureDeviceMapper itemWorkingprocedureDeviceMapper;
    private IOrderItemService iOrderItemService;
    private IDeviceService iDeviceService;

    public ItemWorkingprocedureDeviceServiceImpl(ItemWorkingprocedureDeviceMapper itemWorkingprocedureDeviceMapper, IOrderItemService iOrderItemService, IDeviceService iDeviceService) {
        this.itemWorkingprocedureDeviceMapper = itemWorkingprocedureDeviceMapper;
        this.iOrderItemService = iOrderItemService;
        this.iDeviceService = iDeviceService;
    }

    @Override
    public void batchSave(List<ItemWorkingprocedureDevice> devices) {
        if (null == devices || devices.isEmpty())
            return;

        devices.forEach(itemWorkingprocedureDevice -> {
            itemWorkingprocedureDeviceMapper.insert(itemWorkingprocedureDevice);
            Long deviceId = itemWorkingprocedureDevice.getDeviceId();
            iDeviceService.updateStatus(deviceId, DeviceStatusEnum.GZZ);
        });

        Long orderId = devices.get(0).getOrderId();
        Long itemId = devices.get(0).getItemId();
        OrderItem orderItem = iOrderItemService.findByOrderIdAndItemId(itemId, orderId);
        orderItem.setStatus(OrderItemStatusEnum.DSC);
        iOrderItemService.updateById(orderItem);
    }

    @Override
    public List<ItemWorkingprocedureDevice> findByWorkingprocedureId(long workingprocedureId, long orderId) {
        LambdaQueryWrapper<ItemWorkingprocedureDevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ItemWorkingprocedureDevice::getWorkingProcedureId, workingprocedureId);
        queryWrapper.eq(ItemWorkingprocedureDevice::getOrderId, orderId);
        return itemWorkingprocedureDeviceMapper.selectList(queryWrapper);
    }
}
